import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from login.models import User
from utils.jwttool import tooljwt


class MyAuthentication(BaseAuthentication):
    def authenticate(self,request):
        token = request.META.get('HTTP_AUTHORIZATION', None)
        if not token:
            raise AuthenticationFailed('缺少token')
        tokendata=token.split(' ')[1]
        try:
            decodedata=tooljwt.decodejwt(tokendata)
            userinfo=User.objects.filter(id=decodedata['user']).first()
            if not userinfo:
                raise AuthenticationFailed('用户不存在')
        except jwt.ExpiredSignatureError:
            raise jwt.ExpiredSignatureError('token过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('token无效')
        return None